<?php

class ProductController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
        $model_id = $this->loadModel($id);
        $model_id->scenario = 'admin';
		$this->render('view',array(
			'model'=>$model_id,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Product;
        $model->scenario = 'admin';
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$tmp['on_sale_start'] = date('Y-m-d H:i:s',time());
		$tmp['on_sale_end'] = date('Y-m-d H:i:s',time()+ 30*86400);
		
		$model->attributes=$tmp;
		if(isset($_POST['Product']))
		{
			$tmp = $_POST['Product'];
			
			$product = $tmp;
            $model->image_ = CUploadedFile::getInstance($model,'image_');
			$alias = vn_str_filter_alias($product['name']);
			$image_name = $alias.'.'.$model->image_->extensionName;
            $path = Yii::getPathOfAlias('webroot').'/Uploads/Products/'.$image_name;
            $tmp['image'] = '/Uploads/Products/'.$image_name;
			$criteria = new CDbCriteria();
			$criteria->select = 'MAX(id) as id';
			$product_row = Product::model()->findAll($criteria);
			
			$max_id = sprintf ("%04d",($product_row ? $product_row[0]->id + 1: 0));
			$tmp['alias'] = $alias;
			$p_alias = Category::model()->findAll("id='".$product['category_id']."'");
			$tmp['code'] = $p_alias[0]->alias.$max_id;
			$tmp['creation_datetime'] = date('Y-m-d H:i:s',time());
			$tmp['on_sale'] = str_replace(",","", $product['on_sale']);
			$tmp['last_update'] = date('Y-m-d H:i:s',time());
            $model->attributes=$tmp;
			if($model->save()){
                //The image is valid, you can save it
                if($model->image_)
					$model->image_->saveAs($path);
				$this->redirect(array('view','id'=>$model->id));
            }
		}
        // print_r($model);die;
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
        $model->scenario = 'admin';
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Product']))
		{
			$tmp = $_POST['Product'];
			$tmp['last_update'] = date('Y-m-d H:i:s',time());
			$tmp['on_sale'] = str_replace(",", "", $tmp['on_sale']);
			$model->attributes = $tmp;
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $criteria =new CDbCriteria(array(                    
                                'order'=>'creation_datetime desc',

        ));

		$dataProvider=new CActiveDataProvider('Product',
            array(
            'criteria'=>$criteria,
            )
        );
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		$model->scenario = 'admin'; 
		if(isset($_GET['Product']))
			$model->attributes=$_GET['Product'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Product the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Product::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Product $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='dnd-product-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
function vn_str_filter_alias ($str){

       $unicode = array(

           'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',

           'd'=>'đ',

           'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',

           'i'=>'í|ì|ỉ|ĩ|ị',

           'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',

           'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',

           'y'=>'ý|ỳ|ỷ|ỹ|ỵ',

           'A'=>'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',

           'D'=>'Đ',

           'E'=>'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',

           'I'=>'Í|Ì|Ỉ|Ĩ|Ị',

           'O'=>'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',

           'U'=>'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',

           'Y'=>'Ý|Ỳ|Ỷ|Ỹ|Ỵ',

       );

      foreach($unicode as $nonUnicode=>$uni){

           $str = preg_replace("/($uni)/i", $nonUnicode, $str);

      }

       return strtolower(str_replace(" ","-",$str));

}
